package com.cupk.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cupk.dtos.DashboardDataDto; // 【新增】
import com.cupk.dtos.ProjectDto;
import com.cupk.entities.Project;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.math.BigDecimal; // 【新增】
import java.util.List;

@Mapper
public interface ProjectMapper extends BaseMapper<Project> {

    // 原有方法
    @Select("SELECT p.*, u.full_name as principal_investigator_name " +
            "FROM projects p " +
            "LEFT JOIN project_members pm ON p.id = pm.project_id AND pm.role_in_project = 'PI' " +
            "LEFT JOIN users u ON pm.user_id = u.id")
    List<ProjectDto> findAllWithPiName();

    @Select({
            "<script>",
            "SELECT p.*, u.full_name as principal_investigator_name ",
            "FROM projects p ",
            "LEFT JOIN project_members pm ON p.id = pm.project_id AND pm.role_in_project = 'PI' ",
            "LEFT JOIN users u ON pm.user_id = u.id ",
            "<where>",
            "  <if test='keyword != null and keyword.trim() != \"\"'>",
            "    <choose>",
            "      <when test='searchTag == \"projectName\"'>",
            "        AND p.project_name LIKE CONCAT('%', #{keyword}, '%')",
            "      </when>",
            "      <when test='searchTag == \"projectCode\"'>",
            "        AND p.project_code LIKE CONCAT('%', #{keyword}, '%')",
            "      </when>",
            "      <otherwise>",
            "        AND (p.project_name LIKE CONCAT('%', #{keyword}, '%') OR p.project_code LIKE CONCAT('%', #{keyword}, '%'))",
            "      </otherwise>",
            "    </choose>",
            "  </if>",
            "</where>",
            "ORDER BY p.created_at DESC",
            "</script>"
    })
    Page<ProjectDto> findPageWithPiName(Page<Project> page, @Param("keyword") String keyword, @Param("searchTag") String searchTag);

    // 【在这里添加以下所有新方法】
    long countInProgressForUser(@Param("userId") Long userId);

    long countInProgressForUserLastMonth(@Param("userId") Long userId);

    BigDecimal sumBudgetForUserProjects(@Param("userId") Long userId);

    List<Project> findInProgressWithTaskCountsForUser(@Param("userId") Long userId);

    List<DashboardDataDto.MonthlyChartPoint> getMonthlyTrendForUser(@Param("userId") Long userId, @Param("year") int year);


    List<Project> findRecentCreatedForUser(@Param("userId") Long userId, @Param("limit") int limit);
}